﻿using System.Threading;
using DM4;
using sscore;
using System;
using System.Collections.Generic;
using sscore.Utils;
using System.Text.RegularExpressions;
using System.IO;
using System.Net;
using sscore.Requests;

namespace GA
{
    public class GA : ModuleBase
    {
        private readonly string _searchPage;
        private readonly string _searchUrl;
        private readonly string _offenderLink;
        private readonly string _imageLink;

        private const string StateName = "GA";
        private ResultFile _imagesResultFile;
        readonly string[] _searchParam = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };

        public GA()
        {
            //initialize main system constants
            ModuleCode = "SO_GA";
            Description = "GA Sex Offenders";
            Version = "1.0";

            //for creating sessions
            StartParam = 0;
            StopParam = _searchParam.Length - 1;

            //initialize help 
            AddToHelp(DM4Consts.StartPosition, String.Format("{0}...{1}", StartParam, StopParam));
            AddToHelp(DM4Consts.EndPositon, String.Format("{0}...{1}", StartParam, StopParam));

            AddToHelp(DM4Consts.IsDownload, "true|false");
            AddToHelp(DM4Consts.IsDownloadImg, "true|false");
            AddToHelp(DM4Consts.InsertToDb, "false|true", "(Expected: servername, dbname)");
            AddToHelp(DM4Consts.ServerName, "");
            AddToHelp(DM4Consts.DbName, "");
            AddToHelp(DM4Consts.IsClearDb, "false|true");
            AddToHelp(DM4Consts.TestParam, "false|true");

            Rpm.Codepage = EncodingType.Iso88591;
            RootUrl = "http://services.georgia.gov/";
            _searchPage = RootUrl + "gbi/gbisor/ControllerServlet";
            _searchUrl = _searchPage + "?searchType=all&cmmd=search&city=&zip=&county=&fname=&lname={0}&streetname=&gender=A&incarc=A&start={1}&end={2}";
            _offenderLink = RootUrl + "gbi/gbisor/jsp/Detail.jsp?action=SexualOffenderDetails&sexualoffenderId={0}";
            _imageLink = RootUrl + "gbi/gbisor/ImageServlet?fbiNum={0}";
        }

        private void SetParametersDefaults()
        {
            Params.CreateBooleanParam(DM4Consts.IsDownload, true);
            Params.CreateBooleanParam(DM4Consts.IsDownloadImg, true);
            Params.CreateBooleanParam(DM4Consts.InsertToDb, false);
            Params.CreateBooleanParam(DM4Consts.IsClearDb, false);
            Params.CreateStringParam(DM4Consts.DbName, "");
            Params.CreateStringParam(DM4Consts.ServerName, "");
            Params.CreateIntegerParam(DM4Consts.StartPosition, StartParam);
            Params.CreateIntegerParam(DM4Consts.LastPosition, Params.GetIntegerParam(DmConsts.StartPosition));
            Params.CreateIntegerParam(DM4Consts.EndPositon, StopParam);
            Params.CreateIntegerParam(DM4Consts.LastRecord, 1);
        }

        public override OperationResult Init(IDM4Core iCore, DmTaskParams param)
        {
            //use basic initialization sequence
            base.Init(iCore, param);

            SetParametersDefaults();
            return new OperationResult { Result = DM4Consts.Ok };
        }

        public override OperationResult Start()
        {
            DoWork();
            return new OperationResult { Result = DM4Consts.Ok };
        }

        public override OperationResult DoWork()
        {
            OperationResult or = new OperationResult { Result = DM4Consts.ErrorUnknown };

            if (!Ct.IsCancellationRequested)
            {
                WriteLog("Start parameters:", MessageType.Warning);
                foreach (KeyValuePair<string, string> kvp in Params.GetDictionary()) //get all existing parameters
                    WriteLog(String.Format("Key = {0}, Value = {1}", kvp.Key, kvp.Value), MessageType.Warning);

                if (Params.GetBooleanParam(DM4Consts.IsDownload))
                    Load();

                if (Params.GetBooleanParam(DM4Consts.InsertToDb))
                    if ((Params.GetStringParam(DM4Consts.DbName) == "") || (Params.GetStringParam(DM4Consts.ServerName) == ""))
                    {
                        or.Message = String.Format("{0} or {1} is empty", DM4Consts.DbName, DM4Consts.ServerName);
                        ResultCode = DM4Consts.SessionResultCodeError;
                        ResultMessage = or.Message;
                        UpdateStatus(DmConsts.Error);
                        WriteErrorLog(or.Message); //writting to error and session log   

                        return or;
                    }
                    else
                    {
                        //insert offenders to db 
                        UpdateStatus(DM4Consts.SessionInsertToDb);

                        Offenders.OffInsertToDatabase(StateName, Params.GetStringParam(DmConsts.DbName),
                             Params.GetStringParam(DmConsts.ServerName), ResultDir, Params.GetBooleanParam(DmConsts.IsClearDb),
                             WriteLog);

                    }

                //check if need abort task
                if (Ct.IsCancellationRequested)
                {
                    ResultCode = DM4Consts.SessionResultTerminateByUser;
                    ResultMessage = "Session terminated by user";
                    UpdateStatus(DM4Consts.SessionWait);
                    WriteLog("Session aborted by user", MessageType.Cool);
                }
                else
                {
                    UpdateProgress(1);
                    ResultCode = DM4Consts.SessionResultCodeOk;
                    ResultMessage = String.Format("Session complete, errors : {0}, records : {1}", TaskParams.ErrorCount, TaskParams.RecordCount);
                    UpdateStatus(DM4Consts.SessionComplete);
                    WriteLog("------------Finish----------------", MessageType.Cool);
                }
            }
            else
            {
                ResultCode = DM4Consts.SessionResultTerminateByUser;
                ResultMessage = "Session terminated by user";
                UpdateStatus(DM4Consts.SessionWait);
                WriteLog("Session aborted by user", MessageType.Cool);
            }


            return or;
        }

        private void Load()
        {
            string resultFileName = String.Format("{0}\\{1}.{2}", ResultDir, TaskParams.SessionId, DmConsts.ResultFilesExtension);
            bool workFlag = true;

            ResultFile = new ResultFile(resultFileName, OffendersResult.GetHeader());
            _imagesResultFile = new ResultFile(String.Format("{0}\\{1}_images.{2}", ResultDir, TaskParams.SessionId, DM4Consts.ResultFilesExtension), "FileName|FileUrl");
            try
            {
                while (workFlag)
                {
                    //рабочий цикл
                    string error;

                    try
                    {
                        error = "";  //Required!!  /*if (!String.IsNullOrEmpty(error)) --> restart thread; else --> download finished*/

                        WriteLog("Start download...");
                        Searching();
                    }
                    catch (Exception e)
                    {
                        error = e.Message;
                    }

                    if (!String.IsNullOrEmpty(error))
                    {
                        Thread.Sleep(30000);
                        WriteErrorLog(error);
                        WriteLog("Try continue work...", MessageType.Warning);
                    }
                    else
                    {
                        workFlag = false;  //все нормально откачало, заканчиваем работу
                    }
                }
            }
            finally
            {
                ResultFile.Close();
                _imagesResultFile.Close();
            }
        }

        private void GetCookies()
        {
            WriteLog("get first page");
            string html = GetRequest.ReturnCookies(_searchPage, Rpm);
            Rpm.Cookies = RegExpr.Parse(Rpm.Cookies, "(?si:^([^;]*?);)");

            WriteLog("agree disclaimer page");
            html = PostRedirectRequest.RefererWithCookies(_searchPage, _searchPage, "cmmd=newSearch&disclaimeragree=on&x=32&y=7", Rpm);
            Rpm.Cookies += "; gbisorcookie=1; MasterCookie=MasterCookie";
        }

        private void Searching()
        {
            if (Test)
            {
                Params.SetIntegerParam(DmConsts.LastPosition, Params.GetIntegerParam(DmConsts.StartPosition));
                Params.SetIntegerParam(DmConsts.EndPositon, Params.GetIntegerParam(DmConsts.StartPosition));
            }

            if (Params.GetIntegerParam(DmConsts.EndPositon) > StopParam)
                Params.SetIntegerParam(DmConsts.EndPositon, StopParam);

            GetCookies();
            for (int indSearchParam = Params.GetIntegerParam(DmConsts.LastPosition); indSearchParam <= Params.GetIntegerParam(DmConsts.EndPositon); indSearchParam++)
            {
                //check if need abort task
                if (Ct.IsCancellationRequested)
                    break;

                Params.SetIntegerParam(DmConsts.LastPosition, indSearchParam);
                UpdateProgress();

                WriteLog(string.Format("Process search param [{0}][{1}].",
                    Params.GetIntegerParam(DmConsts.LastPosition),
                    _searchParam[Params.GetIntegerParam(DmConsts.LastPosition)]));
                WriteLog("get first result page with start offender: " + Params.GetIntegerParam(DmConsts.LastRecord));

                do
                {
                    if (Ct.IsCancellationRequested)
                        break;

                    string html = GetRedirectRequest.WithCookies(
                        string.Format(_searchUrl,
                            _searchParam[Params.GetIntegerParam(DmConsts.LastPosition)],
                            Params.GetIntegerParam(DmConsts.LastRecord),
                            Params.GetIntegerParam(DmConsts.LastRecord) + 10),
                        Rpm);

                    if (RegExpr.IsMatch(html, @"(?si:You must agree to the Terms of Use in order to continue)"))
                        throw new Exception(DmConsts.ExcNeedRestart);

                    ParseResultPage(html);
                    if (!RegExpr.IsMatch(html, @"(?si:class=""next"">\&gt;\s*</a>)"))
                        break;
                    WriteLog("navigate to next page, start offender is: " + Params.GetIntegerParam(DmConsts.LastRecord));
                } while (true);

                Params.SetIntegerParam(DmConsts.LastRecord, 1);
            }
        }

        private void ParseResultPage(string html)
        {
            html = HtmlUtils.KillSpace(HtmlUtils.ReplaceSpecSymbols(html.Replace("\r\n", " ").Replace("\t", " ").Replace("\r", " ").Replace("\n", " ")));

            MatchCollection mc = RegExpr.ParseMatchCollection(html, @"(?si:Detail.jsp\x3Faction=SexualOffenderDetails\x26sexualoffenderId=([^""]+)"")");
            WriteLog(String.Format("found [{0}] matches", mc.Count));

            if (mc.Count == 0 && !RegExpr.IsMatch(html, @"(?si:No Offender Found)") && !RegExpr.IsMatch(html, @"(?si:for the State of Georgia)"))
                throw new Exception(DmConsts.ExcNeedRestart + Environment.NewLine + html);

            List<string> list = new List<string>();

            foreach (Match matchLoc in mc)
                if (!list.Contains(matchLoc.Groups[1].Value))
                    list.Add(matchLoc.Groups[1].Value);

            WriteLog(String.Format("found [{0}] id[s]", list.Count));

            foreach (Match matchLoc in mc)
            {
                //check if need abort task
                if (Ct.IsCancellationRequested)
                    break;

                string lookupKey = matchLoc.Groups[1].Value;
                string offenderHtml = GetRequest.WithCookies(string.Format(_offenderLink, lookupKey), Rpm);
                WriteLog(String.Format("ParseOffender [{0}][{1}]", Params.GetIntegerParam(DmConsts.LastRecord), lookupKey));

                if (!RegExpr.IsMatch(offenderHtml, @"(?si:>\s*Search Results\s*<)"))
                    throw new Exception("Offenders page:" + DmConsts.ExcNeedRestart);

                ParseOffender(offenderHtml, lookupKey);
                UpdateRecordCount(1);
                Params.SetIntegerParam(DmConsts.LastRecord, Params.GetIntegerParam(DmConsts.LastRecord) + 1);
            }
        }

        private void ParseOffender(string offenderHtml, string lookupKey)
        {
            offenderHtml = HtmlUtils.KillSpace(HtmlUtils.ReplaceSpecSymbols(offenderHtml.Replace("\r\n", " ").Replace("\t", " ").Replace("\r", " ").Replace("\n", " ")));
            using (OffendersResult or = new OffendersResult())
            {
                or.Source_State = StateName;
                or.offenderLink = string.Format(_offenderLink, lookupKey);
                or.Source_id = lookupKey;

                or.fullname = HtmlUtils.KillSpace(RegExpr.Parse(offenderHtml, @"(?si:NAME\s*:[^<>]*?<B>(.*?)</B>)"));
                or.Ethnicity = HtmlUtils.KillSpace(RegExpr.Parse(offenderHtml, @"(?si:RACE\s*:[^<>]*?<B>(.*?)</B>)"));
                or.sex = HtmlUtils.KillSpace(RegExpr.Parse(offenderHtml, @"(?si:SEX\s*:[^<>]*?<B>(.*?)</B>)"));
                or.Birthdate = HtmlUtils.KillSpace(RegExpr.Parse(offenderHtml, @"(?si:YEAR OF BIRTH\s*:[^<>]*?<B>(.*?)</B>)"));

                or.eye_color = HtmlUtils.KillSpace(RegExpr.Parse(offenderHtml, @"(?si:EYE COLOR\s*:[^<>]*?<B>(.*?)</B>)"));
                or.hair_color = HtmlUtils.KillSpace(RegExpr.Parse(offenderHtml, @"(?si:HAIR COLOR\s*:[^<>]*?<B>(.*?)</B>)"));
                or.height = HtmlUtils.KillSpace(RegExpr.Parse(offenderHtml, @"(?si:HEIGHT\s*:[^<>]*?<B>(.*?)</B>)"));
                or.weight = HtmlUtils.KillSpace(RegExpr.Parse(offenderHtml, @"(?si:WEIGHT\s*:[^<>]*?<B>(.*?)</B>)"));
                or.marks = HtmlUtils.KillSpace(RegExpr.Parse(offenderHtml, @"(?si:SCARS/MARKS/TATTOOS\s*:[^<>]*?<B>(.*?)</B>)"));

                if (or.marks.ToUpper() == "NONE")
                    or.marks = "";

                or.Status = HtmlUtils.KillSpace(RegExpr.Parse(offenderHtml, @"(?si:INCARCERATED\s*:[^<>]*?<B>(.*?)</B>)"));
                or.Status = or.Status == "YES" ? "INCARCERATED" : "";

                or.Address = HtmlUtils.KillSpace(RegExpr.Parse(offenderHtml, @"(?si:ADDRESS\s*:[^<>]*?<B>(.*?)</B>)"));
                if (or.Address == "***INCARCERATED***") or.Address = "";
                or.City = HtmlUtils.KillSpace(RegExpr.Parse(offenderHtml, @"(?si:CITY\s*:[^<>]*?<B>(.*?)</B>)"));
                or.State = HtmlUtils.KillSpace(RegExpr.Parse(offenderHtml, @"(?si:STATE\s*:[^<>]*?<B>(.*?)</B>)"));
                or.Zip = HtmlUtils.KillSpace(RegExpr.Parse(offenderHtml, @"(?si:ZIP\s*:[^<>]*?<B>(.*?)</B>)"));
                or.County = HtmlUtils.KillSpace(RegExpr.Parse(offenderHtml, @"(?si:COUNTY\s*:[^<>]*?<B>(.*?)</B>)"));

                or.registered = HtmlUtils.KillSpace(RegExpr.Parse(offenderHtml, @"(?si:REGISTRATION DATE\s*:[^<>]*?<B>(.*?)</B>)"));
                or.Address_date = HtmlUtils.KillSpace(RegExpr.Parse(offenderHtml, @"(?si:RESIDENCE VERIFICATION DATE\s*:[^<>]*?<B>(.*?)</B>)"));

                or.Crime += "Crime; Conviction date; Conviction State; Absconder/Predator~";
                or.Crime += HtmlUtils.KillSpace(RegExpr.Parse(offenderHtml, @"(?si:CRIME\s*:[^<>]*?<B>(.*?)</B>)")) + ";";
                or.Crime += HtmlUtils.KillSpace(RegExpr.Parse(offenderHtml, @"(?si:CONVICTION DATE\s*:[^<>]*?<B>(.*?)</B>)")) + ";";
                or.Crime += HtmlUtils.KillSpace(RegExpr.Parse(offenderHtml, @"(?si:CONVICTION STATE\s*:[^<>]*?<B>(.*?)</B>)")) + ";";
                or.Crime += HtmlUtils.KillSpace(RegExpr.Parse(offenderHtml, @"(?si:ABSCONDER/PREDATOR\s*:[^<>]*?<B>(.*?)</B>)")) + "~";

                if (Params.GetBooleanParam(DmConsts.IsDownloadImg) && RegExpr.IsMatch(offenderHtml, @"(?si:IMG SRC=""/gbi/gbisor/ImageServlet\?fbiNum=)"))
                {
                    or.Image_ID = Guid.NewGuid() + ".jpg";
                    or.ImageLink = string.Format(_imageLink, or.Source_id);
                    string filePath = String.Format("{0}\\{1}\\{2}", ResultDir, DmConsts.PhotosDir, or.Image_ID);
                    try
                    {
                        string cookies = Rpm.Cookies;
                        Offenders.DownloadImage(_imagesResultFile, filePath, or.ImageLink, TaskParams.SessionId, ref cookies, "", "", "", true, false, true);
                    }
                    catch (WebException ex)
                    {
                        if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotFound)
                        {
                            or.Image_ID = "";
                            or.ImageLink = "";
                        }
                        else throw new Exception(DmConsts.ExcInvalidLoadingImage, ex);
                    }
                    catch (Exception ex)
                    {
                        if (ex.Message.Contains("downloaded image Length is 0"))
                        {
                            if (File.Exists(filePath))
                                File.Delete(filePath);
                            or.Image_ID = "";
                            or.ImageLink = "";
                        }
                        else throw new Exception(DmConsts.ExcInvalidLoadingImage, ex);
                    }
                }

                if (or.Image_ID != "" && !File.Exists(String.Format("{0}\\{1}\\{2}", ResultDir, DmConsts.PhotosDir, or.Image_ID)))
                    throw new Exception(DmConsts.ExcImgNotFound);

                ResultFile.Write(or.GetValues());
            }
        }

        private void UpdateProgress()
        {
            if (Params.GetIntegerParam(DmConsts.StartPosition) > Params.GetIntegerParam(DmConsts.EndPositon))
                throw new Exception(String.Format("Invalid parameters {2}[{0}]; {3} [{1}]",
                    Params.GetIntegerParam(DmConsts.StartPosition), Params.GetIntegerParam(DmConsts.EndPositon),
                    DmConsts.StartPosition, DmConsts.EndPositon));
            if (Params.GetIntegerParam(DmConsts.LastPosition) > Params.GetIntegerParam(DmConsts.EndPositon))
                throw new Exception(String.Format("Invalid parameters {2}[{0}]; {3} [{1}]",
                    Params.GetIntegerParam(DmConsts.LastPosition), Params.GetIntegerParam(DmConsts.EndPositon),
                    DmConsts.StartPosition, DmConsts.EndPositon));
            if (Params.GetIntegerParam(DmConsts.StartPosition) > Params.GetIntegerParam(DmConsts.LastPosition))
                throw new Exception(String.Format("Invalid parameters {2}[{0}]; {3} [{1}]",
                    Params.GetIntegerParam(DmConsts.StartPosition), Params.GetIntegerParam(DmConsts.LastPosition),
                    DmConsts.StartPosition, DmConsts.LastPosition));
            UpdateProgress(((double)(Params.GetIntegerParam(DmConsts.LastPosition) - Params.GetIntegerParam(DmConsts.StartPosition))) / (Params.GetIntegerParam(DmConsts.EndPositon) - Params.GetIntegerParam(DmConsts.StartPosition) + 1));
        }
    }
}
